/* app */
const Koa = require('koa')
const fs = require('fs')
const app = new Koa()

/**
 * Promise 封装 fs.renderFile
 * @param {*} page
 * @returns
 */
function render( page ) {
  return new Promise((resolve, reject) => {
    const viewUrl = `./view/${page}`
    fs.readFile(viewUrl, 'binary', (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

async function route(url) {
  let view = '404.html';
  switch(url) {
    case '/':
    case '/index':
      view = 'index.html'
      break
    case 'todo':
      view = 'todo.html'
      break
    case '/404':
      view = '404.html'
      break
  }

  const html = await render(view)
  return html
}

/* 中间件的引入 */
const loggerAsync = require('./middleware/logger-async')

/* 中间件的使用 */
app.use(loggerAsync())

app.use(async ctx => {
  const url = ctx.request.url
  ctx.body = await route(url)
})

app.listen(4000)

console.log('demo start at port 4000')